require "scripts/include/operative"

bodyId = items("platform1").bodyId

function InitLevel()
	enemyId = dbMakePerson(1000, 0, 2, weapons("shotgun").weaponId, 100)
	items(enemyId).aiMode = 1
	levelEnded = false
	levelEndTime = 0
	playerId = dbGetPlayerId()
	
	dbSetBackgroundColor(0x48A4FF)
end

function UpdateItems()
	ForEachItem(function(item)
		if item.health <= 0.0 then
			local destroy = false
			local bodyId = item.bodyId
			
			if item.bodyId ~= 0 then
				x = b2GetBodyPositionX(bodyId)
				y = b2GetBodyPositionY(bodyId)
				
				if item.attributes:find("X", 1, true) ~= nil then
					dbMakeExplosion(x, y, 500000000.0, 100.0)
					destroy = true
				end
				if item.attributes:find("D", 1, true) ~= nil then
					dbMakeDust(x, y, Argb(128, 255, 200, 150), 20)
					destroy = true
				end
				
				if destroy then
					dbDeleteItem(item.itemId)
				end
			end
		end
	end)
end

function UpdateLevel(deltaTime)
	local x = b2GetBodyPositionX(bodyId)
	if x < 500 then
		b2SetBodyLinearVelocity(bodyId, 100, 0)
	elseif x > 800 then
		b2SetBodyLinearVelocity(bodyId, -100, 0)
	end
	
	UpdateItems()
	
	if levelEnded == false then
		if dbGetEnemyCount() == 0 then
			levelCompleted = true
			levelEnded = true
			levelEndTime = os.time() -- Wait 3 seconds before ending level
		elseif items(playerId).health <= 0.0 then
			levelCompleted = false
			levelEnded = true
			levelEndTime = os.time()
		end
	end
	
	local deltaTime = os.difftime(os.time(), levelEndTime)
		
	-- Return true if level has ended
	return levelEnded and (deltaTime >= 3) -- Wait 3 seconds before ending level
end

function DeinitLevel()
end
